﻿using Abp.BackgroundJobs;
using Abp.Dependency;
using Mt.Site.Core.Synchronization;
using Mt.Site.Core.Synchronization.ContentManagement;
using Mt.Site.Core.Synchronization.Data;
using System;
using System.Threading.Tasks;

namespace Mt.Site.Core.BackGroundJobs.ContentManagement
{
    public class SynchorizationWholeContentJob : AsyncBackgroundJob<BaseAndMenuIdArgs>, ITransientDependency
    {
        private readonly IContentManualSyncManager _contentManualSyncManager;

        private readonly IBackgroundJobManager _backgroundJobManager;

        public readonly ISynchronizationHelper _synchronizationHelper;
        public SynchorizationWholeContentJob (
                IContentManualSyncManager contentManualSyncManager,
                IBackgroundJobManager backgroundJobManager,
                ISynchronizationHelper synchronizationHelper)
        {
            _contentManualSyncManager = contentManualSyncManager;
            _backgroundJobManager = backgroundJobManager;
            _synchronizationHelper = synchronizationHelper;
        }

        public override async Task ExecuteAsync(BaseAndMenuIdArgs args)
        {
            var sonSites = _synchronizationHelper.GetSonSite(args.FromTenantId, args.FromLanguage, args.MenuId);

            foreach (var item in sonSites)
            {
                if (!item.AutoSynchronous)
                {
                    continue;
                }
                var toNewsId = Guid.Empty;
                var createOrUpdateSyncStore = new CreateOrUpdateSynchorizeStore
                {
                    Id = args.Id,
                    TargetLanguage = item.TargetLanguage,
                    ToTenantId = item.TargetTenantId,
                    OptionType = args.OperateType
                };

                toNewsId = await _contentManualSyncManager.CreateOrUpdateContentAutoSync(createOrUpdateSyncStore);
                if (toNewsId != Guid.Empty)
                {
                    var nextSites = _synchronizationHelper.GetSonSite(item.TargetTenantId, item.TargetLanguage, args.MenuId);
                    if (nextSites.Count > 0)
                    {
                        _backgroundJobManager.Enqueue<SynchorizationWholeContentJob , BaseAndMenuIdArgs>(
                            new BaseAndMenuIdArgs
                            {
                                Id = toNewsId,
                                FromLanguage = item.TargetLanguage,
                                FromTenantId = item.TargetTenantId,
                                MenuId = args.MenuId,
                                OperateType = args.OperateType
                            });
                    }
                }
            }
        }
    }
}
